<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/9/6
 * Time: 11:19
 */

use Workerman\Worker;

require_once './workerman/Autoloader.php';

$global_uid = 0;

//当客户端连接上来时分配uid,并保存连接，并通知所有客户端

function handel_connection($connection)
{
    global $text_worker, $global_uid;
    //为这个连接分配一个uid
    $connection->uid = ++$global_uid;
}

//当客户端发来消息过来时，并转发给所有的客户端
function handel_message($connection, $data)
{
    global $text_worker;

    foreach ($text_worker->connections as $conn) {

        $conn->send("user{$connection->uid} say:{$data}");

    }
}

//当客户端断开的时候 广播给所有的客户端
function handel_close($connection)
{
    global $text_worker;

    foreach ($text_worker as $conn) {

        $conn->send("user{$connection->uid} 退出聊天室");
    }
}

//创建一个文本协议的Worker监听2345接口
$text_worker = new Worker("text://0.0.0.0:2345");

//这里至启动一个进程 为了方便客户端之间数据的传输

$text_worker->count = 1;

$text_worker->onConnect='handel_connection';

$text_worker->onMessage='handel_message';

$text_worker->onClose='handle_close';

Worker::runAll();